<script setup lang="ts">
import type { CustomUploadFile } from '@/api/file/type'
import type { Product } from '@/api/product/type'
import type { FormInstance, UploadProps } from 'element-plus'
import { deleteFile, getByTable, upload } from '@/api/file'
import { addProduct, deleteProduct, getById, importExcel, productPage, updateProduct } from '@/api/product'
import ExcelUploadDialog from '@/components/ExcelUploadDialog/index.vue'
import axios from '@/utils/request'
import { Picture, Refresh, Search } from '@element-plus/icons-vue'
import VuePdfEmbed from 'vue-pdf-embed'

const loading = ref(false)
const isDisabled = ref(true)

const productSearch = reactive<Product>({
  name: '',
  code: '',
  specification: '',
  price: 0,
  remark: '',
  pageNo: 1,
  pageSize: 10,
})

const refresh: Product = {
  name: '',
  code: '',
  specification: '',
  price: 0,
  remark: '',
}

const productList = ref<Product[]>()
const total = ref(0)
const queryFormRef = ref(ElForm)

// 查询
function handleQuery() {
  productPage(productSearch).then((pageResult) => {
    productList.value = pageResult.records
    total.value = pageResult.total
  })
}

// 重置
function handleRefresh() {
  queryFormRef.value.resetFields()
  handleQuery()
}

// 改变页容量
function handleSizeChange(val: any) {
  productSearch.pageSize = val
  handleQuery()
}

// 改变页码
function handleCurrentChange(val: any) {
  productSearch.pageNo = val
  handleQuery()
}

// 加载查询
onMounted(() => {
  handleQuery()
})
function onSubmit() {}

const updateDialogVisible = ref(false)
const updateDialogName = ref('产品新增')
const updateFormRef = ref<FormInstance>()
const updateFormData = reactive<Product>({
  name: '',
  code: '',
  specification: '',
  price: 0,
  remark: '',
})

// 保存更新入口
function handleExecute(formEl: FormInstance | any) {
  if (updateFormData.id) {
    handleUpdate(formEl)
  }
  else {
    handleSave(formEl)
  }
}

// 保存
async function handleSave(formEl: FormInstance | any) {
  if (!formEl)
    return
  const isValid = await formEl.validate()
  if (!isValid)
    return
  ElMessageBox.confirm(
    '确认是否新增',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    addProduct(updateFormData).then((msg: any) => {
      ElMessage.success(msg)
      Object.assign(updateFormData, refresh)
      handleQuery()
      updateDialogVisible.value = false
    })
  }).catch(() => ElMessage.info('新增取消'))
}

// 更新
async function handleUpdate(formEl: FormInstance | any) {
  if (!formEl)
    return
  const isValid = await formEl.validate()
  if (!isValid)
    return
  ElMessageBox.confirm(
    '确认是否修改',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    updateProduct(updateFormData).then((msg: any) => {
      ElMessage.success(msg)
      Object.assign(updateFormData, refresh)
      handleQuery()
      updateDialogVisible.value = false
    })
  }).catch(() => ElMessage.info('修改取消'))
}

// 刷新
function refreshProduct() {
  Object.assign(updateFormData, refresh)
}

const updateRules = computed(() => ({
  name: [
    { required: true, message: '请输入产品名称', trigger: 'blur' },
  ],
  code: [
    { required: true, message: '请输入产品编码', trigger: 'blur' },
  ],
}))

// 回显
async function modifyProduct(id: number) {
  const product = await getById(id)
  Object.assign(updateFormData, product)
  updateDialogVisible.value = true
}

const deletedId = ref<Product[]>([])

// 多选
function handleSelectionChange(val: Product[]) {
  isDisabled.value = !val.length
  deletedId.value = val
}

// 删除
function deleteByIds() {
  const ids = deletedId.value?.map(p => p.id!) ?? []
  const name = deletedId.value?.map(p => p.name!) ?? []
  ElMessageBox.confirm(
    `确认是否删除:${name}`,
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    deleteProduct(ids).then((data: any) => {
      ElMessage.success(data)
      handleQuery()
    })
  }).catch(() => ElMessage.info('删除取消'))
}

const detailDialogVisible = ref(false)

// 详情
async function getDetial(id: number) {
  const product = await getById(id)
  Object.assign(updateFormData, product)
  detailDialogVisible.value = true
}

const fileList = ref<CustomUploadFile[]>([])
const uploadDialogVisible = ref(false)
const productId = ref<number>()

const url = ref<string>('')

// 上传对话框，回显文件列表
function uploadFile(id: number) {
  productId.value = id
  getByTable('product', id)
    .then((res: any) => {
      fileList.value = res
      url.value = `${axios.defaults.baseURL}/${res.length > 0 ? res[0].position : ''}`
    })
  uploadDialogVisible.value = true
}

// 上传
const handleUpload: UploadProps['httpRequest'] = async (options) => {
  if (!productId.value)
    return
  const formData = new FormData()
  formData.append('file', options.file)
  formData.append('id', productId.value.toString())
  formData.append('tableName', 'product')
  await upload(formData)
  uploadFile(productId.value)
}

// 上传成功回调
const handleSuccess: UploadProps['onSuccess'] = () => {
  ElMessage.success('文件上传成功！')
}

// 删除文件 removeFile
const onRemove: any = async (option: CustomUploadFile) => {
  const msg: any = await deleteFile(option.id)
  ElMessage.success(msg)
}

// 点击文件
const onPreview: any = (uploadFile: CustomUploadFile) => {
  url.value = `${axios.defaults.baseURL}/${uploadFile.position}`
}

// pdf
// 判断文件类型
const isImage = computed(() => {
  const ext = url.value.split('.').pop()?.toLowerCase() || ''
  return ['jpg', 'jpeg', 'png', 'gif'].includes(ext)
})
const currentPage = ref(1)
const pageCount = ref(0)
const zoomLevel = ref(1)
const rotate = ref(0)
const prevPage = () => currentPage.value = Math.max(1, currentPage.value - 1)
const nextPage = () => currentPage.value = Math.min(pageCount.value, currentPage.value + 1)

function refreshDrawer() {
  productId.value = undefined
  fileList.value = []
  url.value = ''
  currentPage.value = 1
  pageCount.value = 0
  zoomLevel.value = 1
  rotate.value = 0
}

// 导入
const uploadDialog = ref<InstanceType<typeof ExcelUploadDialog> | null>(null)

function handleUploadExcel() {
  uploadDialog.value?.openDialog()
}

async function handleImport(data: FormData) {
  const msg: any = await importExcel(data)
  ElMessageBox.alert(msg.replace(/ +/g, '<br/>'), '导入消息', { confirmButtonText: '确认', dangerouslyUseHTMLString: true })
  handleQuery()
}
</script>

<template>
  <div>
    <el-form ref="queryFormRef" :inline="true" :model="productSearch" class="form-inline">
      <el-form-item label="产品编码" prop="code">
        <el-input v-model="productSearch.code" placeholder="产品编码" />
      </el-form-item>
      <el-form-item label="产品名称" prop="name">
        <el-input v-model="productSearch.name" placeholder="产品名称" />
      </el-form-item>
      <el-form-item>
        <el-button type="success" :icon="Search" @click="handleQuery">
          查询
        </el-button>
        <el-button type="warning" :icon="Refresh" @click="handleRefresh">
          重置
        </el-button>
      </el-form-item>
    </el-form>
    <el-form :inline="true" class="form-operate">
      <el-form-item>
        <el-button type="primary" size="small" plain @click="updateDialogVisible = true">
          新增
        </el-button>
        <el-button type="danger" size="small" plain :disabled="isDisabled" @click="deleteByIds">
          删除
        </el-button>
        <el-button type="success" size="small" plain @click="handleUploadExcel">
          导入
        </el-button>
        <el-button type="warning" size="small" plain :disabled="isDisabled" @click="onSubmit">
          导出
        </el-button>
      </el-form-item>
    </el-form>
    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="productList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column
          type="index"
        />
        <el-table-column
          prop="code"
          label="产品编码"
          width="200"
          align="center"
        />
        <el-table-column
          prop="name"
          label="产品名称"
          width="200"
          align="center"
        />
        <el-table-column
          prop="specification"
          label="规格"
          width="200"
          align="center"
        />
        <el-table-column
          prop="price"
          label="单价"
          width="120"
          align="center"
        />
        <!-- <el-table-column
          prop="customer"
          label="客户"
          width="300"
          align="center"
        /> -->
        <el-table-column fixed="right" label="操作" width="180" align="center">
          <template #default="scope">
            <el-button link type="primary" @click="getDetial(scope.row.id)">
              详情
            </el-button>
            <el-button link type="primary" @click="modifyProduct(scope.row.id)">
              修改
            </el-button>
            <el-button link type="primary" @click="uploadFile(scope.row.id)">
              文件
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pagination"
        :current-page="productSearch.pageNo"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="productSearch.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <div class="update">
      <el-dialog
        v-model="updateDialogVisible"
        :title="updateDialogName"
        width="700px"
        draggable
        @close="refreshProduct()"
      >
        <el-form
          ref="updateFormRef"
          :model="updateFormData"
          :rules="updateRules"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="编码" prop="code">
                <el-input
                  v-model="updateFormData.code"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="名称" prop="name">
                <el-input
                  v-model="updateFormData.name"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="规格" prop="specification">
            <el-input
              v-model="updateFormData.specification"
            />
          </el-form-item>
          <el-row :gutter="20">
            <el-col :span="9">
              <el-form-item label="单价" prop="price">
                <el-input-number v-model="updateFormData.price" :precision="2" :step="0.1" />
              </el-form-item>
            </el-col>
            <el-col :span="15">
              <el-form-item label="客户" prop="customer">
                <el-input
                  v-model="updateFormData.customer"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="updateFormData.remark"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 4 }"
            />
          </el-form-item>
          <div class="dialog-footer">
            <el-button @click="updateDialogVisible = false">
              取消
            </el-button>
            <el-button type="primary" @click="handleExecute(updateFormRef)">
              提交
            </el-button>
          </div>
        </el-form>
      </el-dialog>
    </div>
    <div class="detail">
      <el-dialog
        v-model="detailDialogVisible"
        title="详情"
        width="700px"
        draggable
        @close="refreshProduct()"
      >
        <el-descriptions direction="vertical" border :column="2">
          <el-descriptions-item label="编码">
            {{ updateFormData.code }}
          </el-descriptions-item>
          <el-descriptions-item label="名称">
            {{ updateFormData.name }}
          </el-descriptions-item>
          <el-descriptions-item label="单价">
            {{ updateFormData.price }}
          </el-descriptions-item>
          <el-descriptions-item label="客户">
            kehu
          </el-descriptions-item>
          <el-descriptions-item label="规格" span="2">
            {{ updateFormData.specification }}
          </el-descriptions-item>
          <el-descriptions-item label="备注" span="2">
            {{ updateFormData.remark }}
          </el-descriptions-item>
        </el-descriptions>
      </el-dialog>
    </div>
    <div class="drawer">
      <el-drawer
        v-model="uploadDialogVisible"
        title="文件管理"
        direction="rtl"
        show-close
        size="80%"
        @close="refreshDrawer"
      >
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="custom-upload">
              <el-upload
                v-model:file-list="fileList" multiple
                :http-request="handleUpload" :on-success="handleSuccess"
                :on-remove="onRemove" :on-preview="onPreview"
              >
                <el-button type="primary" size="small" plain>
                  上传文件
                </el-button>
              </el-upload>
            </div>
          </el-col>
          <el-col :span="16">
            <div class="file-preview-container">
              <!-- 图片预览 -->
              <div v-if="isImage" class="image-container">
                <el-image style="width: 100%; height: 100%" :src="url" fit="cover">
                  <template #error>
                    <div class="image-slot">
                      <el-icon><Picture /></el-icon>
                    </div>
                  </template>
                </el-image>
              </div>
              <!-- PDF预览 -->
              <div v-else class="pdf-container">
                <div class="controls-bar">
                  <button @click="prevPage">
                    上一页
                  </button>
                  <span>{{ currentPage }} / {{ pageCount }}</span>
                  <button @click="nextPage">
                    下一页
                  </button>
                  <!-- <button @click="zoomLevel += 0.1">
                    放大
                  </button>
                  <button @click="zoomLevel -= 0.1">
                    缩小
                  </button> -->
                  <button @click="rotate += 90">
                    旋转
                  </button>
                  <button @click="rotate = 0">
                    重置旋转
                  </button>
                </div>
                <div class="pdf-wrapper">
                  <VuePdfEmbed
                    class="pdf-content"
                    :source="url"
                    :page="currentPage"
                    :rotation="rotate"
                    :style="`transform: scale(${zoomLevel})`"
                  />
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-drawer>
    </div>
    <ExcelUploadDialog
      ref="uploadDialog"
      @import-excel="handleImport"
    />
  </div>
</template>

<style scoped>

</style>
